package com.example.administrator.hqq;

import android.app.Application;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.example.administrator.hqq.View.NoScrollViewPager;
import com.example.administrator.hqq.activity.module.AddModuleActivity;
import com.example.administrator.hqq.adapter.FragmentsAdapter;
import com.example.administrator.hqq.base.MyActivity;
import com.example.administrator.hqq.base.MyApplication;
import com.example.administrator.hqq.bean.MainActivityEventData;
import com.example.administrator.hqq.bean.UpApkBean;
import com.example.administrator.hqq.bean.event.RegisterEvent;
import com.example.administrator.hqq.config.LoongsConfig;
import com.example.administrator.hqq.config.UrlFactory;
import com.example.administrator.hqq.fragment.DIspatchTouchEvent;
import com.example.administrator.hqq.fragment.DialogueFragment;
import com.example.administrator.hqq.fragment.DiscoverFragment;
import com.example.administrator.hqq.fragment.InformationFragment;
import com.example.administrator.hqq.fragment.MineFragment;
import com.example.administrator.hqq.fragment.discover.ConventionDlalogFragment;
import com.example.administrator.hqq.service.AppMqttService;
import com.example.administrator.hqq.service.DownloadAPKService;
import com.example.administrator.hqq.utils.AlertDialogUtil;
import com.example.administrator.hqq.utils.GetLocationUtils;
import com.example.administrator.hqq.utils.RongIMUtils;
import com.example.administrator.hqq.utils.systembartint.StatusBarUtil;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.rong.imkit.RongIM;
import io.rong.imkit.manager.IUnReadMessageObserver;
import io.rong.imlib.model.Conversation;
import me.leolin.shortcutbadger.ShortcutBadger;
import okhttp3.Call;


public class MainActivity extends MyActivity {
    @BindView(R.id.main_vp)
    NoScrollViewPager mainVp;
    @BindView(R.id.main_rg)
    RadioGroup mainRg;
    @BindView(R.id.find_image)
    ImageView findImage;
    @BindView(R.id.dialogue_image)
    ImageView dialogueImage;
    @BindView(R.id.message_image)
    ImageView messageImage;
    @BindView(R.id.mine_image)
    ImageView mineImage;
    @BindView(R.id.hint)
    TextView hint;
    @BindView(R.id.discover_text)
    TextView discoverText;
    @BindView(R.id.dialogue_text)
    TextView dialogueText;
    @BindView(R.id.information_text)
    TextView informationText;
    @BindView(R.id.mine_text)
    TextView mineText;
    @BindView(R.id.dialog_number)
    TextView dialogNumber;
    @BindView(R.id.message_number)
    TextView messageNumber;
    @BindView(R.id.convention_module_guide)
    ImageView conventionModuleGuide;
    private int index = 0;
    private String TAG = this.getClass().getSimpleName();
    private List<Fragment> fragments;
    private List<TextView> textViews;
    private DIspatchTouchEvent dIspatchTouchEvent;
    private ConventionDlalogFragment conventionDlalogFragment;
    private DiscoverFragment discoverFragment;
    private boolean isShow=true;
    private ProgressDialog progressDialog;
    private Intent serviceIntent;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);//防止键盘弹出扰乱布局
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy( builder.build() );
        }
        //当FitsSystemWindows设置 true 时，会在屏幕最上方预留出状态栏高度的 padding
        StatusBarUtil.setRootViewFitsSystemWindows(this, false);
//        //设置状态栏透明
        StatusBarUtil.setTranslucentStatus(this);
        //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
        ButterKnife.bind(this);
        RongIMUtils.connect(SPUtils.getInstance().getString(LoongsConfig.rongToken), this);
        EventBus.getDefault().register(this);
        initview();
        initdata();
        initUpApk();
        setUserLocation();
        NotificationManagerCompat manager = NotificationManagerCompat.from(this);
        boolean isOpened = manager.areNotificationsEnabled();
        boolean aBoolean = SPUtils.getInstance().getBoolean(LoongsConfig.isOpenedNotification, false);
        if (!isOpened && !aBoolean) {
            new AlertDialog.Builder(this)
                    .setMessage("需要开启通知权限")
                    .setPositiveButton("去设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            Intent intent = new Intent();
                            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", MainActivity.this.getPackageName(), null);
                            intent.setData(uri);
                            startActivity(intent);
                        }
                    })
                    .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            SPUtils.getInstance().put(LoongsConfig.isOpenedNotification, true);
                            ToastUtils.showShort("你已拒绝,该功能将不可用");
                            dialog.dismiss();
                        }
                    })
                    .show();
        }
        //开启MQtt消息队列
        serviceIntent = new Intent(this, AppMqttService.class);
        startService(serviceIntent);
    }

    /**
     * 更新Apk
     */
    private void initUpApk() {
        OkHttpUtils.get().url(UrlFactory.checkAndroidVersion())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "更新ApkonError: "+e.getMessage() );
            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "更新ApkonResponse: "+response );
                Gson gson = new Gson();
                final UpApkBean upApkBean = gson.fromJson(response, UpApkBean.class);
                if (upApkBean.getCode()==200)
                {
                    if (!AppUtils.getAppVersionName().equals(upApkBean.getVersion()))
                    AlertDialogUtil.showTitleAlertDialog(MainActivity.this, "有新版本可更新", upApkBean.getText(), new AlertDialogUtil.AlertDialogClick.ConfirmClick() {
                        @Override
                        public void confirm() {
                            //开启下载更新任务
                            Intent intent = new Intent(MainActivity.this, DownloadAPKService.class);
                            intent.putExtra(LoongsConfig.url,upApkBean.getUrl());
                            startService(intent);
                        }
                    });
                }
            }
        });
    }

    private void setUserLocation() {
        if (TextUtils.isEmpty(GetLocationUtils.getLocation()))
        {
            GetLocationUtils.getloction(getApplicationContext());
            SPUtils.getInstance().put( LoongsConfig.city_code,"010");
            SPUtils.getInstance().put(LoongsConfig.location,"116.292103,39.946878");
            Log.e(TAG, "setUserLocation: "+"获取地理位置为空" );
        }
        else{

        }
        OkHttpUtils.get().url(UrlFactory.setUserLocation())
                .addParams(LoongsConfig.user_id, LoongsConfig.getUser_id())
                .addParams(LoongsConfig.location, GetLocationUtils.getLocation())
                .addParams(LoongsConfig.city_code, GetLocationUtils.getCityCode())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, "onError: " + e.getMessage());

            }

            @Override
            public void onResponse(String response, int id) {
                Log.e(TAG, "onResponse: " + response);
            }
        });
    }

    private void initdata() {
        //监听融云未读消息的数量
        RongIM.getInstance().addUnReadMessageCountChangedObserver(new IUnReadMessageObserver() {
            @Override
            public void onCountChanged(int i) {
                Log.e(TAG, "未读消息: " + i);
                if (i > 0) {
                    dialogNumber.setVisibility(View.VISIBLE);
                    dialogNumber.setText(i + "");
                    ShortcutBadger.applyCount(MainActivity.this, i);
                } else {
                    ShortcutBadger.removeCount(MainActivity.this);
                    dialogNumber.setVisibility(View.GONE);
                }
                if (i > 99) {
                    dialogNumber.setText("...");
                }

            }
        }, Conversation.ConversationType.GROUP, Conversation.ConversationType.PRIVATE);
    }

    private void initview() {
        RegisterEvent registerEvent = new RegisterEvent();
        registerEvent.setType(RegisterEvent.Type.BACK);
        EventBus.getDefault().post(registerEvent);
        fragments = new ArrayList<>();
        textViews = new ArrayList<>();
        textViews.add(discoverText);
        textViews.add(dialogueText);
        textViews.add(informationText);
        textViews.add(mineText);
        mainRg.getChildAt(0).setSelected(true);
        //发现fragment
        discoverFragment = new DiscoverFragment();
        //对话
        DialogueFragment dialogueFragment = new DialogueFragment();
        //消息
        InformationFragment informationFragment = new InformationFragment();
        //我的
        MineFragment mineFragment = new MineFragment();
        //贴子群聊
        conventionDlalogFragment = new ConventionDlalogFragment();
        fragments.add(discoverFragment);
        fragments.add(dialogueFragment);
        fragments.add(informationFragment);
        fragments.add(mineFragment);
        fragments.add(conventionDlalogFragment);
        mainVp.setOffscreenPageLimit(5);
        FragmentsAdapter fragmentsAdapter = new FragmentsAdapter(getSupportFragmentManager(), fragments);
        mainVp.setAdapter(fragmentsAdapter);
        mainVp.setCurrentItem(0);
        textViews.get(0).setTextColor(Color.parseColor("#000000"));
        for (int i = 0; i < mainRg.getChildCount(); i++) {
            final int finalI = i;
            mainRg.getChildAt(i).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    changeFragment(finalI);
                }
            });
        }
        //更新消息计数显示
        informationFragment.setInformationNumber(new InformationFragment.InformationNumber() {
            @Override
            public void setMainInformationNumber() {
                int notification_number = LoongsConfig.getUsersIdSPUtils().getInt(LoongsConfig.MessageNotification.InformationNotificationNumber, 0);
                int message_number = LoongsConfig.getUsersIdSPUtils().getInt(LoongsConfig.MessageNotification.InformationMessageNumber, 0);
                messageNumber.setVisibility(View.VISIBLE);
                int anInt = message_number + notification_number;
                if (anInt <= 0) {
                    messageNumber.setVisibility(View.GONE);
                } else if (anInt > 0 && anInt <= 99) {
                    messageNumber.setText(anInt + "");
                } else {
                    messageNumber.setText("…");
                }
                LoongsConfig.getUsersIdSPUtils().put(LoongsConfig.MessageNotification.InformationNumber, notification_number + message_number);
            }
        });
        mineFragment.setAddModule(new MineFragment.AddModule() {
            @Override
            public void addModule(String category_id) {
                //设置我的页面的点击全部模块事件
                Intent intent1 = new Intent(MainActivity.this, AddModuleActivity.class);
                intent1.putExtra(LoongsConfig.type, AddModuleActivity.Type.MODIFICATION);
                intent1.putExtra(LoongsConfig.data, (Serializable) discoverFragment.getData());
                intent1.putExtra(LoongsConfig.category_id, category_id);
                startActivity(intent1);
            }
        });
        informationFragment.setAddModule(new MineFragment.AddModule() {
            @Override
            public void addModule(String category_id) {
                Intent intent1 = new Intent(MainActivity.this, AddModuleActivity.class);
                intent1.putExtra(LoongsConfig.type, AddModuleActivity.Type.MODIFICATION);
                intent1.putExtra(LoongsConfig.data, (Serializable) discoverFragment.getData());
                intent1.putExtra(LoongsConfig.category_id, category_id);
                startActivity(intent1);
            }
        });
        int notification_number = LoongsConfig.getUsersIdSPUtils().getInt(LoongsConfig.MessageNotification.InformationNotificationNumber, 0);
        int message_number = LoongsConfig.getUsersIdSPUtils().getInt(LoongsConfig.MessageNotification.InformationMessageNumber, 0);
        messageNumber.setVisibility(View.VISIBLE);
        int anInt = message_number + notification_number;
        Log.e(TAG, "Event: " + anInt);
        if (anInt <= 0) {
            messageNumber.setVisibility(View.GONE);
        } else if (anInt > 0 && anInt <= 99) {
            messageNumber.setText(anInt + "");
        } else {
            messageNumber.setText("…");
        }
        LoongsConfig.getUsersIdSPUtils().put(LoongsConfig.MessageNotification.InformationNumber, notification_number + message_number);
    }

    private void changeFragment(int i) {
        for (int i1 = 0; i1 < mainRg.getChildCount(); i1++) {
            mainRg.getChildAt(i1).setSelected(false);
            textViews.get(i1).setTextColor(Color.parseColor("#CCCAC7"));
            if (i1 == i) {
                if (i1 == 0) {
                    mainVp.setCurrentItem(index);
                    mainRg.getChildAt(i1).setSelected(true);
                } else {
                    mainVp.setCurrentItem(i);
                    mainRg.getChildAt(i1).setSelected(true);
                }
                if (i1 == 2) {
                    setInformationNumber();
                }
                textViews.get(i).setTextColor(Color.parseColor("#000000"));
            }
        }
    }

    /**
     * 更新消息计数显示
     */
    private void setInformationNumber() {
        int notification_number = LoongsConfig.getUsersIdSPUtils().getInt(LoongsConfig.MessageNotification.InformationNotificationNumber, 0);
        int message_number = LoongsConfig.getUsersIdSPUtils().getInt(LoongsConfig.MessageNotification.InformationMessageNumber, 0);
        InformationFragment fragment = (InformationFragment) fragments.get(2);
        if (fragment.getNormalAuto()) {
            message_number = 0;
            LoongsConfig.getUsersIdSPUtils().put(LoongsConfig.MessageNotification.InformationMessageNumber, message_number);
        } else {
            notification_number = 0;
            LoongsConfig.getUsersIdSPUtils().put(LoongsConfig.MessageNotification.InformationNotificationNumber, notification_number);
        }
        messageNumber.setVisibility(View.VISIBLE);
        int anInt = message_number + notification_number;
        if (anInt <= 0) {
            messageNumber.setVisibility(View.GONE);
        } else if (anInt > 0 && anInt <= 99) {
            messageNumber.setText(anInt + "");
        } else {
            messageNumber.setText("…");
        }
        LoongsConfig.getUsersIdSPUtils().put(LoongsConfig.MessageNotification.InformationNumber, notification_number + message_number);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void Event(MainActivityEventData mainActivityEventData) {
        index = mainActivityEventData.getIndex();
        mainVp.setCurrentItem(index);
        if (mainActivityEventData.getTopic_id() != null)
        {
            boolean aBoolean = SPUtils.getInstance().getBoolean(LoongsConfig.first_convention_module, true);
            if (aBoolean) {
                isShow = true;
                conventionModuleGuide.setVisibility(View.VISIBLE);
                conventionModuleGuide.setImageDrawable(getDrawable(R.drawable.convention_guide_image1));
                SPUtils.getInstance().put(LoongsConfig.first_convention_module, false);
            }
            conventionDlalogFragment.setTopic_id(mainActivityEventData.getTopic_id());
        }
        conventionDlalogFragment.setTopicName(mainActivityEventData.getTopic_name()+"圈圈");
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (dIspatchTouchEvent != null) {
            dIspatchTouchEvent.onDispatchTouchEvent(ev);
        }
        return super.dispatchTouchEvent(ev);
    }

    public void setdIspatchTouchEvent(DIspatchTouchEvent dIspatchTouchEvent) {
        this.dIspatchTouchEvent = dIspatchTouchEvent;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        stopService(serviceIntent);
    }

    private long time = -1;

    @Override
    public void onBackPressed() {
        if (index == 4) {
            index = 0;
            mainVp.setCurrentItem(index);
        } else {
            moveTaskToBack(true);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected String getActivityName() {
        return this.getClass().getSimpleName();
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @OnClick(R.id.convention_module_guide)
    public void onViewClicked() {
        if (!isShow)
            conventionModuleGuide.setVisibility(View.GONE);
        isShow=false;
        conventionModuleGuide.setImageDrawable(getDrawable(R.drawable.convention_guide_image2));
    }

}
